<template>
  <div class="app_main">
    <div class="search_box">
      <el-form ref="searchForm" :inline="true" :model="searchForm" size="mini">
        <search-form-box>
          <template slot="showSearch">
            <el-form-item label="甲方名称" prop="part_a">
              <el-input v-model="searchForm.part_a" placeholder="请输入甲方名称" clearable/>
            </el-form-item>
            <el-form-item label="合同编号" prop="contract_num">
              <el-input v-model="searchForm.contract_num" placeholder="请输入合同编号" clearable/>
            </el-form-item>
            <el-form-item label="子公司" prop="dept_id">
              <el-select v-model="searchForm.dept_id" clearable style="width: 200px">
                <el-option v-for="item in companyArr" :key="item.id" :value="item.id" :label="item.head"/>
              </el-select>
            </el-form-item>
            <el-form-item label="客户" prop="customer_id">
              <el-select v-model="searchForm.customer_id" filterable clearable style="width: 200px">
                <el-option v-for="item in customerArr" :key="item.id" :value="item.id" :label="item.name"/>
              </el-select>
            </el-form-item>
          </template>
          <template slot="hideSearch">
            <el-form-item label="下单时间" prop="fill_date_begin">
              <el-date-picker
                v-model="searchForm.fill_date_begin"
                type="date"
                placeholder="开始时间"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd"
                clearable
              />
            </el-form-item>
            <el-form-item label="至" prop="fill_date_end">
              <el-date-picker
                v-model="searchForm.fill_date_end"
                type="date"
                placeholder="结束时间"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd"
                clearable
              />
            </el-form-item>
            <el-form-item label="投放时间" prop="contractBeginDate">
              <el-date-picker
                v-model="searchForm.contractBeginDate"
                type="date"
                placeholder="开始时间"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd"
                clearable
              />
            </el-form-item>
            <el-form-item label="至" prop="contractEndDate">
              <el-date-picker
                v-model="searchForm.contractEndDate"
                type="date"
                placeholder="结束时间"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd"
                clearable
              />
            </el-form-item>
            <el-form-item label="分组名称" prop="group_id">
              <el-select v-model="searchForm.group_id" clearable style="width: 200px">
                <el-option v-for="item in searchGroupArr" :key="item.id" :value="item.id" :label="item.name"/>
              </el-select>
            </el-form-item>
          </template>
          <template slot="searchBtn">
            <el-form-item>
              <el-button size="mini" type="primary" plain @click="search">查询</el-button>
              <el-button size="mini" type="info" plain @click="resetForm('searchForm')">重置</el-button>
            </el-form-item>
          </template>
        </search-form-box>
      </el-form>
    </div>
    <div style="margin-bottom: 10px" class="flex flex-no-wrap justify-between">
      <div class="flex flex-no-wrap">
        <el-button v-permission="'create_sale_order'" size="mini" type="primary" @click="saleTypeDialogVisible = true">
          新增销售单
        </el-button>
        <el-button size="mini" type="primary" @click="addGroupRelation">
          新建分组
        </el-button>
      </div>
      <div v-loading="btnLoading" style="text-align: right">
        <el-badge v-if="unHandledNum" :value="unHandledNum">
          <el-button v-permission="'sale_account_received_list'" size="mini" type="primary"
                     @click="accountReceivedPageDialogVisible = true"
          >
            到款列表
          </el-button>
        </el-badge>
        <el-button v-permission="'sale_account_received_list'" v-else size="mini" type="primary"
                   @click="accountReceivedPageDialogVisible = true"
        >
          到款列表
        </el-button>
      </div>
    </div>
    <div class="data_box">
      <el-table v-loading="tableLoading" :data="tableData" border style="width: 100%" size="mini" @selection-change="handleSelectionChange"
      :max-height="tableMaxHeight" :row-style="getRowStyle">
        <el-table-column type="selection" width="55" :selectable="selected"/>
        <el-table-column fixed="left" width="50" label="序号" align="center">
          <template slot-scope="scope">
            <span>{{ (listParams.page - 1) * listParams.page_size + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="分组名称" min-width="100" prop="groupName" align="center" show-overflow-tooltip />
        <el-table-column label="甲方抬头" min-width="180" prop="contractName" align="center" show-overflow-tooltip />
        <el-table-column label="合同编号" min-width="120" prop="contract_num" align="center" show-overflow-tooltip />
        <el-table-column label="客户名称" min-width="150" prop="customerName" align="center" show-overflow-tooltip />
        <el-table-column label="合同金额" width="120" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.contractAmount }}元</span>
          </template>
        </el-table-column>
        <el-table-column label="下单金额" width="120" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.execute_amount }}元</span>
          </template>
        </el-table-column>
        <el-table-column label="已执行金额" width="120" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.total_executed_amount > 0 ? scope.row.total_executed_amount : 0 }}元</span>
          </template>
        </el-table-column>
        <el-table-column label="未执行金额" width="120" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.contractAmount > scope.row.total_executed_amount ? (scope.row.contractAmount - scope.row.total_executed_amount) : 0 }}元</span>
          </template>
        </el-table-column>
        <el-table-column label="下单时间" width="120" prop="fill_date" align="center"/>
        <el-table-column label="换画类型" width="100" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.type === 1" type="primary" size="mini">否</el-tag>
            <el-tag v-else type="success" size="mini">是</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="监播发送" width="100" align="center">
          <template slot-scope="scope">
            <el-tag v-if="!scope.row.send_or_not" type="info" size="mini">未发送</el-tag>
            <el-tag v-else type="success" size="mini">已发送</el-tag>
          </template>
        </el-table-column>
		<el-table-column label="发票" width="80" align="center">
		  <template slot-scope="scope">
		    <el-tag v-if="!scope.row.groupInvoiceReceived" type="info" size="mini">未收</el-tag>
		    <el-tag v-else type="success" size="mini">已收</el-tag>
		  </template>
		</el-table-column>
        <el-table-column label="审核状态" width="100" align="center" >
          <template slot-scope="scope">
            <el-tag v-if="scope.row.flow_status == 3" size="mini">流程中</el-tag>
            <el-tag v-if="scope.row.flow_status == 4" type="success" size="mini">已通过</el-tag>
            <el-tag v-if="scope.row.flow_status == 0" type="info" size="mini">草稿</el-tag>
            <el-tag v-if="scope.row.flow_status == 2" type="danger" size="mini">被退回</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag v-if="!scope.row.mode" type="success" size="mini">有效</el-tag>
            <el-tag v-if="scope.row.mode == 1" type="warning" size="mini">挂起</el-tag>
            <el-tag v-if="scope.row.mode == 2" type="danger" size="mini">作废</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="所属子公司" width="100" align="center" prop="deptName"/>
        <el-table-column label="其他约定" prop="memo" align="center" min-width="200px"
                         show-overflow-tooltip/>
        <el-table-column fixed="right" label="操作" width="240" align="center">
          <template slot-scope="scope">
            <el-button-group class="btn_group_box">
              <el-tooltip effect="dark" content="建市场单" placement="top" v-permission="'look_my_sale_order'" v-if="scope.row.canCreate != null && scope.row.canCreate > 0">
                <el-button size="mini" icon="el-icon-plus" @click="createMarketBill(scope.row.id,scope.row.type)"></el-button>
              </el-tooltip>
              <el-tooltip effect="dark" content="查看" placement="top" v-permission="'look_my_sale_order'">
                <el-button size="mini" icon="el-icon-view" @click="look(scope.row.id)"></el-button>
              </el-tooltip>
              <el-tooltip effect="dark" content="查看变更前的销售单" placement="top" v-permission="'look_my_sale_order'" v-if="(scope.row.originList || []).length > 0">
                <el-button size="mini" icon="el-icon-time" @click="look(scope.row.originList[0].id)"></el-button>
              </el-tooltip>
              <el-tooltip effect="dark" content="变更" placement="top" v-if="scope.row.mode === 1">
                <el-button type="primary" size="mini" icon="el-icon-edit" @click="updateSaleOrder(scope.row.id)"></el-button>
              </el-tooltip>
              <el-tooltip effect="dark" content="撤单" placement="top" v-if="scope.row.flow_status === 4 && scope.row.mode !== 2" v-permission="'look_my_sale_order'">
                <el-button size="mini" icon="el-icon-refresh-left" @click="handleCancel(scope.row.id)"></el-button>
              </el-tooltip>
              <el-tooltip effect="dark" content="确认监播发送" placement="top"
              v-if="scope.row.flow_status === 4 && !scope.row.send_or_not" v-permission="'confirm_monitor_btn'">
                <el-button type="success" size="mini" icon="el-icon-finished" @click="confirmMonitor(scope.row.id)"></el-button>
              </el-tooltip>
              <el-tooltip effect="dark" content="上传结算材料" placement="top"
                        v-if="scope.row.flow_status === 4 && scope.row.send_or_not" v-permission="'upload_appendix_btn'">
                <el-button type="primary" size="mini" icon="el-icon-upload2" @click="showUploadAppendixDialog(scope.row)"></el-button>
              </el-tooltip>
              <el-tooltip effect="dark" content="所属分组发票已收" placement="top"
                        v-if="scope.row.flow_status === 4 && !scope.row.groupInvoiceReceived" v-permission="'confirm_group_receive_invoice'">
                <el-button type="warning" size="mini" icon="el-icon-document-checked" @click="confirmGroupInvoiceReceive(scope.row.id)"></el-button>
              </el-tooltip>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-pagination
      :current-page.sync="searchForm.page"
      :page-sizes="[10, 20, 50, 100, 200, 400]"
      :page-size.sync="searchForm.page_size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      style="margin-top: 10px"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"/>

    <el-dialog title="结算材料" :visible.sync="uploadAppendixDialogVisible" width="30%" center @open="getAppendixListById"
               @close="closeUploadAppendixDialog"
    >
      <div v-loading="uploadAppendixDialogLoading">
        <el-upload
          :action="upFileUrl" :headers="uploadHeaders"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :before-remove="beforeRemove"
          :on-success="uploadingSuccess"
          :before-upload="beforeUpload"
          :on-error="uploadError"
          :file-list="billSaleAppendixForm.appendixList"
        >
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
      </div>
      <!--      <el-card shadow="always">-->
      <!--        <div v-if="billSaleAppendixForm.appendixList && billSaleAppendixForm.appendixList.length > 0"-->
      <!--             class="flex flex-wrap align-start"-->
      <!--        >-->
      <!--          <div v-for="(appendix,index) in billSaleAppendixForm.appendixList" :key="index">-->
      <!--            <el-card shadow="always">-->
      <!--              <div style="text-align: center">-->
      <!--                <el-tag type="primary">{{ appendix.name }}</el-tag>-->
      <!--              </div>-->
      <!--              <div>-->
      <!--                <el-button type="primary" size="mini" @click="download(appendix.url)">下载</el-button>-->
      <!--                <el-button type="danger" size="mini" @click="remove(index)">删除</el-button>-->
      <!--              </div>-->
      <!--            </el-card>-->
      <!--          </div>-->
      <!--        </div>-->
      <!--        <div v-else style="text-align: center">-->
      <!--          暂无-->
      <!--        </div>-->
      <!--      </el-card>-->
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="uploadAppendixDialogVisible = false">关 闭</el-button>
        <el-button size="mini" type="primary" @click="save">保 存</el-button>
      </span>
    </el-dialog>

    <el-dialog title="方案" :visible.sync="centerDialogVisible" width="30%" center @close="closeDialog">
      <el-card v-loading="loading" shadow="always">
        <el-row v-if="tmp !== null" :gutter="20">
          <el-col :span="12" style="text-align: center">
            客户名称：{{ tmp.customer_name }}
          </el-col>
          <el-col :span="12" style="text-align: center">
            方案名称：{{ tmp.plan_name }}
          </el-col>
          <el-col :span="12" style="text-align: center">
            开始时间：{{ tmp.daterange_start_at }}
          </el-col>
          <el-col :span="12" style="text-align: center">
            结束时间：{{ tmp.daterange_end_at }}
          </el-col>
          <el-col :span="24" style="text-align: center">
            锁定点位数：{{ tmp.lock_count }}
          </el-col>
        </el-row>
        <div v-else style="text-align: center">
          {{ '暂无关联的方案' }}
        </div>
      </el-card>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" size="mini" @click="toUpdateSaleOrder">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="销售单类型" :visible.sync="saleTypeDialogVisible" width="300px" center @close="closeSaleTypeDialog">
      <el-form size="mini" style="width: 260px;margin: 0 auto">
        <el-form-item label="类型">
          <el-radio-group v-model="type">
            <el-radio :label="1">普通</el-radio>
            <el-radio :label="2">换画</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="saleTypeDialogVisible = false">取 消</el-button>
        <el-button type="primary" size="mini" @click="createSaleOrder">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="销售单撤单" :visible.sync="saleCancelDialogVisible" width="300px" center @close="closeSaleCancelDialog">
      <el-form size="mini" style="width: 260px;margin: 0 auto">
        <el-form-item label="撤单原因">
          <el-input v-model="reason" type="textarea" placeholder="请输入撤单原因" :rows="4"/>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="saleCancelDialogVisible = false">取 消</el-button>
        <el-button type="primary" size="mini" @click="cancelSaleOrder">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="到款列表" :visible.sync="accountReceivedPageDialogVisible" width="80%" center @open="getDialogList"
               @close="getUnHandledNum"
    >
      <div class="search_box">
        <el-form ref="accountReceivedSearchForm" :inline="true" :model="accountReceivedSearchForm" size="mini">
          <search-form-box :show-more-btn="false">
            <template slot="showSearch">
              <el-form-item label="到款开始时间" prop="begin_time">
                <el-date-picker
                  v-model="accountReceivedSearchForm.begin_time"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="请选择开始时间"
                />
              </el-form-item>
              <el-form-item label="至" prop="end_time">
                <el-date-picker
                  v-model="accountReceivedSearchForm.end_time"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="请选择结束时间"
                />
              </el-form-item>
              <el-form-item label="客户" prop="customer_id">
                <el-select v-model="accountReceivedSearchForm.customer_id" filterable clearable style="width: 200px">
                  <el-option v-for="item in customerArr" :key="item.id" :value="item.id" :label="item.name"/>
                </el-select>
              </el-form-item>
            </template>
            <template slot="searchBtn">
              <el-form-item>
                <el-button size="mini" type="primary" plain @click="accountReceivedSearch">查询</el-button>
                <el-button size="mini" type="info" plain @click="accountReceivedResetForm">重置</el-button>
              </el-form-item>
            </template>
          </search-form-box>
        </el-form>
      </div>
      <div class="data_box">
        <el-table v-loading="accountReceivedTableLoading" :data="listData" border size="mini">
          <el-table-column fixed="left" width="50" label="序号" align="center">
            <template slot-scope="scope">
              <span>
                {{ (accountReceivedListParams.page - 1) * accountReceivedListParams.page_size + scope.$index + 1 }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="是否关联组别" width="120" align="center">
            <template slot-scope="scope">
              <el-tag size="mini" v-if="scope.row.group_id !== null" type="success">已关联</el-tag>
              <el-tag size="mini" v-else type="danger">未关联</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="到款时间" min-width="120" prop="account_received_time" align="center"/>
          <el-table-column label="付款客户" min-width="120" prop="customer_name" align="center"/>
          <el-table-column label="到款金额" min-width="120" prop="account" align="center"/>
          <el-table-column label="组别名称" min-width="120" prop="account" align="center">
            <template slot-scope="scope">
              <el-tooltip effect="dark" placement="top">
                <div slot="content">
                  <div>组别所含销售单信息</div>
                  <div v-for="(item,index) in scope.row.billSaleVOS" :key="index">
                    {{ item.contract_num + '——' + item.actual_execute_time_start + '~' + item.actual_execute_time_end }}
                  </div>
                </div>
                <div>{{ scope.row.group_name }}</div>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" align="center">
            <template slot-scope="scope">
              <el-button v-if="scope.row.group_id === null" type="primary" size="mini"
                         @click="showRelationGroupDialog(scope.row.id, scope.row.customer_id)"
              >关联组别
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination
        :current-page.sync="accountReceivedSearchForm.page"
        :page-sizes="[10, 20, 50, 100, 200, 400]"
        :page-size.sync="accountReceivedSearchForm.page_size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="accountReceivedTotal"
        style="margin-top: 10px"
        @size-change="handleAccountReceivedSizeChange"
        @current-change="handleAccountReceivedCurrentChange"
      />
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="accountReceivedPageDialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>

    <el-dialog title="关联组别" :visible.sync="relationGroupDialogVisible"
               :width="groupRelationRequest.type===1?'20%':'60%'" append-to-body center
               @close="closeRelationGroupDialog"
    >
      <el-form ref="cuForm" size="mini" :model="groupRelationRequest" :rules="groupRelationRequestRules">
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="groupRelationRequest.type" @change="typeChange">
            <el-radio :label="1">已有分组</el-radio>
            <el-radio :label="2">新建分组</el-radio>
          </el-radio-group>
        </el-form-item>
        <div v-if="groupRelationRequest.type === 2">
          <el-form-item class="bill_sale_form_item" label="销售单">
            <el-transfer v-loading="selectLoading"
                         v-model="groupRelationRequest.bill_sale_ids" :titles="['所有销售单', '合成一组的销售单']" filterable
                         :data="optionData"
                         @change="handleChange"
            >
              <span slot-scope="{ option }">
                <el-tooltip placement="top">
                  <div slot="content">所属公司：{{  option.deptName }}<br/>资源类型：{{ option.mediaTypeName }}<br/>执行金额：{{ option.execute_amount }}</div>
                  <div>{{ option.label }}</div>
                </el-tooltip>
              </span>
            </el-transfer>
            <div style="color: #F56C6C;margin-left: 60px">合成一组以后只能由财务修改,请认真选择后再提交</div>
          </el-form-item>
          <el-form-item label="分组名称" prop="name">
            <el-input v-model="groupRelationRequest.name" clearable style="width: 300px" placeholder="请输入分组名称"
            ></el-input>
          </el-form-item>
        </div>
        <div v-else>
          <el-form-item label="组别" prop="group_id">
            <el-select v-loading="selectLoading" v-model="groupRelationRequest.group_id" placeholder="请选择组别" clearable
                       filterable
            >
              <el-tooltip v-for="group in groupArr" :key="group.id" effect="dark" placement="right">
                <div slot="content">
                  <div>组别所含销售单信息</div>
                  <div v-for="(item,index) in group.saleVOList" :key="group.id+''+index">
                    {{ item.contract_num + '——' + item.actual_execute_time_start + '~' + item.actual_execute_time_end }}
                  </div>
                </div>
                <el-option :label="group.name" :value="group.id"></el-option>
              </el-tooltip>
            </el-select>
          </el-form-item>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="relationGroupDialogVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="submitForm">提 交</el-button>
      </span>
    </el-dialog>

		<relation-group-dialog ref="RelationGroupDialogRef" @relationSubmitted="getDialogList"></relation-group-dialog>
		<SaleOrderDialog ref="SaleOrderDialog" :saleOrderId="lookOriginId"/>
  </div>
</template>

<script>
import SearchFormBox from '@/components/SearchFormBox'
import {
  confirmMonitor, getAppendixListById, list, listNew,
  uploadAppendix, relation as add_group_relation, list_group as search_list_group, confirmGroupInvoiceReceive, cancel
} from '@/api/saleOrder'
import { get_company } from '@/api/system/department'
import { generateUUID } from '@/utils/util'
import { listByRelated } from '@/api/business/intention_scheme'
import { list_all } from '@/api/customer/customer'
import { upFileUrl } from '@/api/others'
import { getToken } from '@/utils/auth'
import { countUnHandled, salePage } from '@/api/accountReceived'
import { relation, saleList, list as groupList, list_by_account_received_id } from '@/api/saleOrder/bill_sale_group'
import RelationGroupDialog from './components/RelationGroupDialog.vue';
import SaleOrderDialog from './components/SaleOrderDialog';

export default {
  name: 'My',
  components: { SearchFormBox, RelationGroupDialog, SaleOrderDialog },
  data() {
    return {
      reason: null,
      columnShow: false,
      tableMaxHeight: 0,
      tableData: [],
      tableLoading: false,
      searchForm: {
        page: 1,
        page_size: 10,
        // 客户名称
        part_a: null,
        // 填表日期开始
        fill_date_begin: null,
        // 填表日期结束
        fill_date_end: null,
        // 分公司id
        dept_id: null,
        // 投放开始时间
        contractBeginDate: null,
        // 投放结束时间
        contractEndDate: null,
        manager: false,
        contract_num: null,
        customer_id: null,
        group_id: null
      },
      listParams: {
        page: 1,
        page_size: 10,
        // 客户名称
        part_a: null,
        // 填表日期开始
        fill_date_begin: null,
        // 填表日期结束
        fill_date_end: null,
        // 分公司id
        dept_id: null,
        // 投放开始时间
        contractBeginDate: null,
        // 投放结束时间
        contractEndDate: null,
        manager: false,
        contract_num: null,
        customer_id: null
      },
      companyArr: [],
      customerArr: [],
      total: null,
      centerDialogVisible: false,
      saleTypeDialogVisible: false,
      saleCancelDialogVisible: false,
      tmp: null,
      loading: false,
      tmpSaleId: null,
      type: 1,
      uploadAppendixDialogVisible: false,
      billSaleAppendixForm: {
        bill_sale_id: null,
        appendixList: []
      },
      upFileUrl,
      uploadHeaders: {},
      uploading: null,
      uploadAppendixDialogLoading: false,
      unHandledNum: 0,
      btnLoading: false,
      accountReceivedPageDialogVisible: false,
      accountReceivedSearchForm: {
        page: 1,
        page_size: 10,
        customer_id: null,
        begin_time: null,
        end_time: null
      },
      accountReceivedListParams: {
        page: 1,
        page_size: 10,
        customer_id: null,
        begin_time: null,
        end_time: null
      },
      accountReceivedTotal: 0,
      listData: [],
      accountReceivedTableLoading: false,
      groupRelationRequest: {
        name: null,
        account_received_id: null,
        type: 1,
        bill_sale_ids: [],
        group_id: null,
        customer_id: null
      },
      groupRelationRequestRules: {
        name: [
          { required: true, message: '请输入分组名称', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ],
        group_id: [
          { required: true, message: '请选择分组', trigger: 'change' }
        ]
      },
      relationGroupDialogVisible: false,
      optionData: [],
      selectLoading: false,
      groupArr: [],
      searchGroupArr:[],
      multipleSelection: [],
	    lookOriginId: null,
    }
  },
  created() {
    this.tableMaxHeight = (document.documentElement.clientHeight || document.body.clientHeight) - 210
    this.initCompanyArr()
    this.initCustomerArr()
    this.initGroupArr()
    this.getList()
    this.getUnHandledNum()
    if (getToken()) {
      this.uploadHeaders['Authorization'] = getToken()
    }

  },
  methods: {
    getRowStyle(row, index){
      return {
        background: row.mode == 2 ? '#ff5722' : '#fff'
      };
    },
	  lookOrigin(id) {
	    this.lookOriginId = id
	    this.$refs.SaleOrderDialog.open()
	  },
    selected(row, index) {
    	if (row.groupId) {
    		return false //不可勾选
    	} else {
    		return true; //可勾选
    	}
    },
    handleSelectionChange(val){
      this.multipleSelection = val.map(item => {
        return {
          id: item.id,
          contract_id: item.contract_id
        }
      })
    },
    addGroupRelation(){
      console.log(this.multipleSelection)
      if(!this.multipleSelection.length) {
        this.$message.warning('请先勾选需要分组的销售单')
        return
      }
      var map = new Map()
      this.multipleSelection.map(item => {
        console.log(item)
        var id = item.id, contract_id = item.contract_id
        if(map.has(contract_id)) map.get(contract_id).push(id)
        else map.set(contract_id,[id])
      })
      if(map.size > 1) {
        this.$message.warning('所选销售单中不是同一个合同，请重新勾选')
        return
      }

      this.$prompt('请输入分组名称', '新建分组', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^.{1,200}$/,
        inputErrorMessage: '分组名称至少1位字符串，最长不超过200位字符串'
      }).then(({ value }) => {
        this.$confirm('提交后只能由财务修改，确定继续', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          var bill_sale_ids = []
          map.forEach((value,index)=>{
            bill_sale_ids = value
          })
          var postData = {
            name:value,
            bill_sale_ids: bill_sale_ids
          }
          const loading = this.$loading({
            lock: true,
            text: '提交中',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          add_group_relation(postData).then(res => {
            this.$message.success('操作成功')
            this.initGroupArr()
            this.getList()
            loading.close()
          }).catch(() => {
            loading.close()
          })
        }).catch(() => {

        })
      }).catch(() => {

      });
    },
    handleSizeChange(val) {
      this.listParams.page_size = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listParams.page = val
      this.getList()
    },
    getList() {
      this.tableLoading = true
      listNew(this.listParams).then(res => {
        this.tableLoading = false
        this.total = res.data.total
        this.tableData = res.data.records
      }).catch(() => {
        this.tableLoading = false
      })
    },
    search() {
      this.searchForm.page = 1
      this.listParams = Object.assign({}, this.searchForm)
      this.getList()
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.listParams = Object.assign({}, this.searchForm)
      this.getList()
    },
    createSaleOrder() {
      const uuid = generateUUID()
      this.$store.commit('keep/PUT_PAGE_PARAMS', {
        uuid: uuid,
        data: {
          is_create: true,
          type: this.type
        }
      });
      //隐藏蒙层
      this.saleTypeDialogVisible = false;
      this.$router.push({
        name: 'create_sale_order_detail_new',
        query: {
          uuid
        }
      })
    },
    handleCancel(id){
      this.bill_id = id;
      this.saleCancelDialogVisible = true;
    },
    cancelSaleOrder(){
      const req = {};
      req.bill_sale_id = this.bill_id;
      req.reason = this.reason;
      cancel(req).then(res => {
        console.log(res)
        this.$message.success('撤单申请提交成功！')
        this.reason = '';
        this.saleCancelDialogVisible = false
      }).catch(() => {
        this.saleCancelDialogVisible = false
      })
    },
    createMarketBill(id,type){
      const uuid = generateUUID()
      this.$store.commit('keep/PUT_PAGE_PARAMS', {
        uuid: uuid,
        data: {
          is_create: true,
          type: type,
          bill_sale_id: id
        }
      })
      this.$router.push({
        name: 'create_market_order_new',
        query: {
          uuid
        }
      })
    },
    toUpdateSaleOrder() {
      if (this.tmp === null) {
        this.$message.error('未关联方案')
        return
      }
      const uuid = generateUUID()
      this.$store.commit('keep/PUT_PAGE_PARAMS', {
        uuid: uuid,
        data: {
          is_create: true,
          is_update: true,
          plan_id: this.tmp.id,
          customer_id: this.tmp.before_update_sale_customer_id,
          contract_id: this.tmp.before_update_sale_contract_id,
          source_sale_id: this.tmpSaleId
        }
      })
      this.$router.push({
        name: 'create_sale_order_detail_new',
        query: {
          uuid
        }
      })
    },
    /**
     * 初始化子公司数组
     */
    initCompanyArr() {
      get_company().then(res => {
        this.companyArr = res.data
      })
    },
    /**
     * 初始化分组名称数组
     */
    initGroupArr() {
      search_list_group().then(res => {
        this.searchGroupArr = res.data
      })
    },
    look(id) {
      const title = '查看销售单'
      const uuid = generateUUID()
      this.$store.commit('keep/PUT_PAGE_PARAMS', {
        uuid: uuid,
        data: {
          id: id
        }
      })
      if (id >= 765){
        this.$router.push({
          name: 'my_sale_order_new',
          query: {
            uuid,
            title
          }
        })
      }else {
        this.$router.push({
          name: 'sale_order_detail',
          query: {
            uuid
          }
        })
      }
    },
    cancel(id) {
      const title = '销售单撤单'
      const uuid = generateUUID()
      this.$store.commit('keep/PUT_PAGE_PARAMS', {
        uuid: uuid,
        data: {
          id: id
        }
      })
      if (id >= 765){
        this.$router.push({
          name: 'my_sale_order_new',
          query: {
            uuid,
            title
          }
        })
      }
    },
    updateSaleOrder(id) {
      this.loading = true
      this.tmpSaleId = id
      this.centerDialogVisible = true
      listByRelated({ related_type: 2, related_id: id }).then(res => {
        if (res.data.length > 0) {
          this.tmp = res.data[0]
        }
        this.loading = false
      })
    },
    closeDialog() {
      this.tmp = null
      this.tmpSaleId = null
    },
    closeSaleTypeDialog() {
      this.type = 1
    },
    initCustomerArr() {
      list_all().then(res => {
        this.customerArr = res.data
      })
    },
    confirmMonitor(id) {
      this.$confirm('是否确认监播已发送？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '提交中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        confirmMonitor({ id }).then(res => {
          this.$message.success('操作成功')
          this.getList()
          loading.close()
        }).catch(() => {
          loading.close()
        })
      }).catch(() => {

      })
    },
	// 确认所属组别，发票已收
	confirmGroupInvoiceReceive(id){
		this.$confirm('是否确认所属组别的发票已经收到？', '提示', {
		  confirmButtonText: '确定',
		  cancelButtonText: '取消',
		  type: 'warning'
		}).then(() => {
		  const loading = this.$loading({
		    lock: true,
		    text: '提交中',
		    spinner: 'el-icon-loading',
		    background: 'rgba(0, 0, 0, 0.7)'
		  })
		  confirmGroupInvoiceReceive({ id }).then(res => {
		    this.$message.success('操作成功')
		    this.getList()
		    loading.close()
		  }).catch(() => {
		    loading.close()
		  })
		}).catch(() => {

		})
	},
    showUploadAppendixDialog(row) {
      this.billSaleAppendixForm.bill_sale_id = row.id
      this.uploadAppendixDialogVisible = true
    },
    closeUploadAppendixDialog() {
      this.billSaleAppendixForm = {
        bill_sale_id: null,
        appendixList: []
      }
    },
    getAppendixListById() {
      this.uploadAppendixDialogLoading = true
      getAppendixListById({ id: this.billSaleAppendixForm.bill_sale_id }).then(res => {
        this.uploadAppendixDialogLoading = false
        this.billSaleAppendixForm.appendixList = res.data
      })
    },
    download(url) {
      if (url) {
        window.open(url, '_blank')
      } else {
        this.$message.error('文件不存在')
      }
    },
    handleRemove(file, fileList) {
      let flag = false
      for (let i = 0; i < this.billSaleAppendixForm.appendixList.length; i++) {
        if (this.billSaleAppendixForm.appendixList[i].url === file.url) {
          this.billSaleAppendixForm.appendixList.splice(i, 1)
          flag = true
          break
        }
      }
      if (!flag) {
        this.$message.error('删除失败！请联系管理员')
      }
    },
    handlePreview(file) {
      if (file.url) {
        window.open(file.url, '_blank')
      } else {
        this.$message.error('文件不存在')
      }
    },
    beforeRemove(file) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    uploadingSuccess(res, file, fileList) {
      this.billSaleAppendixForm.appendixList.push({
        name: file.name,
        url: res.data,
        bill_sale_id: this.billSaleAppendixForm.bill_sale_id
      })
      this.uploading.close()
    },
    uploadError() {
      this.uploading.close()
    },
    beforeUpload() {
      this.uploading = this.$loading({
        lock: true,
        text: '上传中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
    },
    save() {
      if (this.billSaleAppendixForm.appendixList && this.billSaleAppendixForm.appendixList.length) {
        const loading = this.$loading({
          lock: true,
          text: '保存中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        uploadAppendix(this.billSaleAppendixForm.appendixList).then(res => {
          this.uploadAppendixDialogVisible = false
          this.$message.success('保存成功')
          loading.close()
        }).catch(() => {
          loading.close()
        })
      } else {
        this.$message.error('至少上传一个文件')
      }
    },
    getUnHandledNum() {
      this.btnLoading = true
      countUnHandled().then(res => {
        this.unHandledNum = res.data
        this.btnLoading = false
      }).catch(() => {

      })
    },
    handleAccountReceivedSizeChange(val) {
      this.accountReceivedListParams.page_size = val
      this.getDialogList()
    },
    handleAccountReceivedCurrentChange(val) {
      this.accountReceivedListParams.page = val
      this.getDialogList()
    },
    getDialogList() {
      this.accountReceivedTableLoading = true
      salePage(this.accountReceivedListParams).then(res => {
        this.listData = res.data.records
        this.accountReceivedTotal = res.data.total
        this.accountReceivedTableLoading = false
      }).catch(() => {
        this.accountReceivedTableLoading = false
      })
    },
    accountReceivedSearch() {
      this.accountReceivedListParams = Object.assign({}, this.accountReceivedSearchForm)
      this.getDialogList()
    },
    accountReceivedResetForm() {
      this.$refs.accountReceivedSearchForm.resetFields()
      this.accountReceivedSearch()
    },
    showRelationGroupDialog(id, customer_id) {
      /* this.groupRelationRequest.account_received_id = id
      this.groupRelationRequest.customer_id = customer_id
      this.relationGroupDialogVisible = true
      this.getGroupArr(); */
			this.$refs.RelationGroupDialogRef.openThis({
				account_received_id: id,
				customer_id: customer_id
			});
    },
    closeRelationGroupDialog() {
      this.groupRelationRequest = {
        name: null,
        account_received_id: null,
        type: 1,
        bill_sale_ids: [],
        group_id: null
      }
      this.$nextTick(() => {
        this.$refs.cuForm.clearValidate()
      })
    },
    typeChange(val) {
      if (val === 1) {
        this.groupRelationRequest.bill_sale_ids = []
        this.groupRelationRequest.name = null
        this.getGroupArr()
      } else {
        this.groupRelationRequest.group_id = null
        this.getSaleList()
      }
      this.$nextTick(() => {
        this.$refs.cuForm.clearValidate()
      })
    },
    handleChange(val) {
      console.log(val)
    },
    getSaleList() {
      this.selectLoading = true
      saleList({
        customer_id: this.groupRelationRequest.customer_id
      }).then(res => {
        this.selectLoading = false
        this.optionData = res.data.map(item => {
          return {
            key: item.id,
            label: item.customerName + '——' + item.actual_execute_time_start + '~' + item.actual_execute_time_end,
            deptName: item.deptName,
            mediaTypeName: item.mediaTypeName,
            execute_amount: item.execute_amount
          }
        })
      }).catch(() => {
        this.optionData = []
      })
    },
    getGroupArr() {
      this.selectLoading = true
      /* groupList().then(res => {
        this.selectLoading = false
        this.groupArr = res.data
      }).catch(() => {

      }); */
	  list_by_account_received_id({
		  acId: this.groupRelationRequest.account_received_id
	  }).then(res => {
	    this.selectLoading = false
	    this.groupArr = res.data
	  }).catch(() => {

	  })
    },
    submitForm() {
      this.$refs.cuForm.validate(flag => {
        if (flag) {
          if (this.groupRelationRequest.type === 2 && (!this.groupRelationRequest.bill_sale_ids || this.groupRelationRequest.bill_sale_ids.length === 0)) {
            this.$message.error('请选择至少一个销售单')
            return
          }
          this.$confirm('合成一组以后只能由财务修改，确定继续', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            const loading = this.$loading({
              lock: true,
              text: '提交中',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            })
            relation(this.groupRelationRequest).then(res => {
              this.$message.success('操作成功')
              this.relationGroupDialogVisible = false
              this.getDialogList()
              loading.close()
            }).catch(() => {
              loading.close()
            })
          }).catch(() => {

          })
        }
      })
    }
  }
}
</script>

<style scoped>
.app_main {
  padding: 20px;
}

/deep/ .el-transfer-panel {
  width: 400px;
}

/deep/ .bill_sale_form_item .el-form-item__label:before {
  content: "*";
  color: #F56C6C;
  margin-right: 4px;
}
.btn_group_box span {
  float: left;
}
</style>
